package com.ailanyin.modules.job.controller;

import com.ailanyin.common.base.result.AjaxResult;
import com.ailanyin.common.database.result.CommonPage;
import com.ailanyin.common.poi.utils.ExcelUtil;
import com.ailanyin.modules.job.domain.SysJob;
import com.ailanyin.modules.job.exceptions.TaskException;
import com.ailanyin.modules.job.service.SysJobService;
import com.github.pagehelper.PageHelper;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 调度任务信息操作处理
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/monitor/job")
public class SysJobController {
    @Autowired
    private SysJobService jobService;

    /**
     * 查询定时任务列表
     */
    @GetMapping("/list")
    public CommonPage list(SysJob sysJob,
                           @RequestParam(value = "pageSize" , defaultValue = "5") Integer pageSize,
                           @RequestParam(value = "pageNum" , defaultValue = "1") Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        List<SysJob> list = jobService.selectJobList(sysJob);
        return CommonPage.restPage(list);
    }

    /**
     * 导出定时任务列表
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysJob sysJob) {
        List<SysJob> list = jobService.selectJobList(sysJob);
        ExcelUtil.exportExcel(list, SysJob.class, "定时任务" , response);

    }

    /**
     * 获取定时任务详细信息
     */
    @GetMapping(value = "/{jobId}")
    public AjaxResult getInfo(@PathVariable("jobId") Long jobId) {
        return AjaxResult.success(jobService.selectJobById(jobId));
    }

    /**
     * 新增定时任务
     */
    @PostMapping
    public AjaxResult add(@RequestBody SysJob job) throws SchedulerException, TaskException {
        return AjaxResult.toAjax(jobService.insertJob(job));
    }

    /**
     * 修改定时任务
     */
    @PutMapping
    public AjaxResult edit(@RequestBody SysJob job) throws SchedulerException, TaskException {
        return AjaxResult.toAjax(jobService.updateJob(job));
    }

    /**
     * 定时任务状态修改
     */
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysJob job) throws SchedulerException {
        SysJob newJob = jobService.selectJobById(job.getJobId());
        newJob.setStatus(job.getStatus());
        return AjaxResult.toAjax(jobService.changeStatus(newJob));
    }

    /**
     * 定时任务立即执行一次
     */
    @PutMapping("/run")
    public AjaxResult run(@RequestBody SysJob job) throws SchedulerException {
        jobService.run(job);
        return AjaxResult.success();
    }

    /**
     * 删除定时任务
     */
    @DeleteMapping("/{jobIds}")
    public AjaxResult remove(@PathVariable Long[] jobIds) throws SchedulerException, TaskException {
        jobService.deleteJobByIds(jobIds);
        return AjaxResult.success();
    }
}
